﻿<?php
/*
Plugin Name: Distant Quiz
Plugin URI: http://
Description: Плагин позволяет формировать тесты и оценивать остаточные знания
Author: Каминская Ю., Панасюк О.
Version: 1.0
Author URI: http://
*/

register_activation_hook(__FILE__, "distant_quiz_activate");
register_deactivation_hook(__FILE__, "distant_quiz_deactivate");
register_uninstall_hook(__FILE__, "distant_quiz_uninstall");

function distant_quiz_activate()
{
    include plugin_dir_path(__FILE__) . "classes/Installer.php";

    $installer = new Installer();

    $installer->createGroupsTable();
    $installer->createQuizzesTable();
    $installer->createQuestionsTable();
    $installer->createAnswersTable();
    $installer->createResultsTable();

    $installer->createRelQuizToGroupsTable();
    $installer->createRelTutorToGroupsTable();
    $installer->createRelStudentToGroupTable();

    global $wp_rewrite;

    $quiz_url = plugins_url("quiz.php", __FILE__);
    $quiz_url = substr($quiz_url, strlen(home_url()) + 1);
    $wp_rewrite->add_external_rule("quiz.php$", $quiz_url . '?id=$matches[1]');

    $quiz_result_url = plugins_url("quiz-result.php", __FILE__);
    $quiz_result_url = substr($quiz_result_url, strlen(home_url()) + 1);
    $wp_rewrite->add_external_rule("quiz-result.php$", $quiz_result_url . '?id=$matches[1]');

//    $quiz_results_url = plugins_url("quiz-results.php", __FILE__);
//    $quiz_results_url = substr($quiz_results_url, strlen(home_url()) + 1);
//    $wp_rewrite->add_external_rule("quiz-results.php$", $quiz_results_url . '?id=$matches[1]');

    $wp_rewrite->flush_rules();
}

function distant_quiz_deactivate()
{
//    include plugin_dir_path( __FILE__ ) . "classes/Installer.php";
//    $installer = new Installer();
//    $installer->removeQuestionsTable();
//    $installer->removeAnswersTable();
}

function distant_quiz_uninstall()
{
//    include plugin_dir_path( __FILE__ ) . "classes/Installer.php";
//    $installer = new Installer();
//    $installer->removeGroupsTable();
}

add_action("admin_menu", "register_dq_admin_menu_page");
function register_dq_admin_menu_page()
{
    add_menu_page(
        "Тестирование",
        "Тестирование",
        "publish_posts",
        "distant-quiz/admin.php",
        "",
        plugins_url("distant-quiz/images/admin-panel-icon.png"),
        26
    );

    add_submenu_page(
        null, //"distant-quiz/admin.php"
        "Создать тест",
        "Создать тест",
        "publish_posts",
        "distant-quiz/quiz-form.php"
    );

    add_submenu_page(
        null,
        "Создать вопрос",
        "Создать вопрос",
        "publish_posts",
        "distant-quiz/question-form.php"
    );

    add_submenu_page(
        null,
        "Создать группу",
        "Создать группу",
        "publish_posts",
        "distant-quiz/group-form.php"
    );

    add_submenu_page(
        null,
        "Результаты теста",
        "Результаты теста",
        "publish_posts",
        "distant-quiz/quiz-results.php"
    );
}

class distant_quiz_widget extends WP_Widget
{
    function __construct()
    {
        $name = __("Тесты для студентов", "distant_quiz_widget_domain");
        $description = __(
            "В данном виджете выводятся тесты для студентов",
            "distant_quiz_widget_domain"
        );

        parent::__construct(
            "distant_quiz_widget",
            $name,
            array("description" => $description)
        );
    }

    public function widget($args, $instance)
    {
        $currentUser = wp_get_current_user();
        $role = $currentUser->roles[0];
        if ($currentUser->ID == 0 || $role != "contributor") {
            return;
        }

        define("BASE_DQ_PLUGIN_PATH", plugin_dir_path(__FILE__));
        require_once BASE_DQ_PLUGIN_PATH . "classes/QuizDao.php";
        require_once BASE_DQ_PLUGIN_PATH . "classes/UserDao.php";
        require_once BASE_DQ_PLUGIN_PATH . "classes/ResultDao.php";

        $quizDao = new QuizDao();
        $userDao = new UserDao();
        $resultDao = new ResultDao();

        $student = $userDao->getById($currentUser->ID, UserDao::ROLE_STUDENT);
        $groupId = isset($student->groups[0]) ? $student->groups[0] : 0;
        $quizzes = $quizDao->getByGroupId($groupId);

        $title = apply_filters("widget_title", $instance["title"]);
        echo $args["before_widget"];
        if (!empty($title)) {
        }
        echo $args["before_title"] . $title . $args["after_title"];
        if ($groupId == 0) {
            echo "<b style='color: red;'>Внимание!</b>
                В данных учетной записи не указана ваша учебная группа.<br>
                Обратитесь к преподавателю или администрации сайта.";
            return;
        }?>
        <ul>
            <? foreach ($quizzes as $quiz) { ?>
                <? $results = $resultDao->getAllByQuizUser($quiz->id, $student->id); ?>
                <li>
                    <a href="/quiz.php?id=<?= $quiz->id ?>">
                        <?= $quiz->name ?>
                        <?= (count($results) > 0) ? "&nbsp;(Результаты)" : ""?>
                    </a>
                </li>
            <? } ?>
        </ul>
        <?echo $args["after_widget"];
    }

    public function form($instance)
    {
        if (isset($instance["title"])) {
            $title = $instance["title"];
        } else {
            $title = __("Тесты для студентов", "distant_quiz_widget_domain");
        }
        ?>

        <p>

            <label for="<?php echo $this->get_field_id("title"); ?>">
                <?php _e("Title:"); ?>
            </label>
            <input id="<?php echo $this->get_field_id("title"); ?>"
                   type="text"
                   class="widefat"
                   name="<?php echo $this->get_field_name("title"); ?>"
                   value="<?php echo esc_attr($title); ?>"/>
        </p>

    <?php
    }

    public function update($new_instance, $old_instance)
    {
        $instance = array();
        $instance["title"] =
            (!empty($new_instance["title"])) ?
                strip_tags($new_instance["title"]) : '';
        return $instance;
    }
}

function distant_quiz_load_widget()
{
    register_widget("distant_quiz_widget");
}

add_action("widgets_init", "distant_quiz_load_widget");